import socket
import engine
import thread, sys

_PORT = 5555

class Server:
	def __init__(self):
		self.sock = socket.socket()
		self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
		self.users = [None, None, None, None]
		self.numUsers = 0
		self.engine = engine.Engine()
		self.table = [1,1,1,1]
		
	def close(self):
		self.sock.close()	
		print("closing connection")
		
	def connect(self, port):
		self.sock.bind(('', port))
		self.sock.listen(4)
		print("listening....")
		while(self.numUsers < 4):
			client, addr = self.sock.accept();
			self._chooseTable(client)
			#self.users.append((self.numUsers, name, client))
			#client.send(str(self.numUsers)+"wait for other players to join!")
			self.numUsers += 1
			#print(self.numUsers)
		print("all users connected!")
		self.engine.start(self.users)
		
	def _chooseTable(self, client):
		name = client.recv(32)
		print "got player name"
		tbl = self._tableToString()
		print tbl
		client.send(tbl)
		print "send table view to player"
		ch = client.recv(1)
		chair = int(ch) 
		print "got seat selection from player"
		while (self.table[chair-1] == 0):
			chair += 1
		print "actual seat for player = " + str(chair) 
		self.users[chair-1] = (chair-1, name, client)
		self.table[chair-1] = 0
		print("player " + name + " sat on chair " + str(chair))
		client.send(str(chair-1)+"wait for other players to join!")
		
	def _tableToString(self):
		st = ""
		for i in self.table:
			st = st + str(i) + ":"
		st = st.rstrip(":")
		print(st)
		return st
		
def exit(s):
	i = raw_input()
	s.close()
	sys.exit()
	
def startServer():
	s.connect(_PORT)
	print("game has ended. restart server for a new game")
	sys.exit()
	
if(__name__ == '__main__'):
	s = Server()
	thread.start_new_thread(startServer, ())
	exit(s)